import { createRouter, createWebHistory } from 'vue-router'
const getAllRoutes = () => {
  //获取view下所有index.vue
  const requireContext = import.meta.glob('@/views/**/index.vue', { eager: true })
  //提取路径
  const keys = Object.entries(requireContext).map(([key]) => key)

  let routes = keys.map((key) => {
    //文件全路径 包括文件名 ：/user/index.vue
    const allPath = key.split('/views')[1]
    const mainPathArr = key.split('/')
    //层级
    const level = mainPathArr.length - 4
    //父级路由地址
    const parentPath =
      level === 1 ? null : '/' + mainPathArr.slice(3, mainPathArr.length - 2).join('/')
    //路由地址
    const path = '/' + mainPathArr.slice(3, mainPathArr.length - 1).join('/')
    // console.log(mainPath)
    const componentsModule = requireContext[key]?.default;
    const meta = componentsModule?.meta || {}
    const routeItem = {
      allPath,
      name: pathToName(path),
      path,
      parentPath,
      level,
      meta,
      //import.meta.glob 获取的比 import 多一层 default
      component: componentsModule
    }
    return routeItem
  })
  return routes
}

/**
 * 将路径转化为名称
 * @param {*} name
 * @returns pathName
 */
const pathToName = function (name) {
  // eslint-disable-next-line no-useless-escape
  const SPECIAL_CHARS_REGEXP = /([\/]+(.))/g
  //去掉路径的/并替换每个/后面的第一个字母，除了首字母外转为大写
  return name.replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) {
    return offset ? letter.toUpperCase() : letter
  })
}

/**
 * 将路由列表转为路由树
 * @param {*} items
 * @returns rootItems
 */
function arrayToTree(items) {
  const rootItems = []
  const lookup = {}

  for (const item of items) {
    const itemId = item.path
    lookup[itemId] = item
    const parentId = item.parentPath
    if (parentId === null) {
      rootItems.push(item)
    } else {
      const parent = lookup[parentId]
      if (parent) {
        ; (parent.children || (parent.children = [])).push(item)
      }
    }
  }
  return rootItems
}

//路由列表
const allRoutes = getAllRoutes()
//路由树
const allRoutesTree = arrayToTree(allRoutes)
console.table(allRoutesTree)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/home.vue'),
      children: [...allRoutesTree]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login.vue')
    }
  ]
})

export default router
